/*
 * This file is part of LexiToolsMobile
 *  
 * Author: Jerzy Wawro, Jozef Kamycki
 * ver. 1.00
 * Copyright: Tenar (http://www.tenar.pl)
 *
 * Mobile LexiTools is an open source project; you can redistribute it 
 * and/or modify it under the terms of the license as published -  GPL with 
 * the following modification:  fragments of the code may be not copyleft 
 * (hidden), to protect contents of the dicionaries.
 * In this case the author of non-public fragments of the code is obliged 
 * to make available functionally equivalent code for unprotected dictionaries.
 * 
 * Mobile LexiTools is distributed WITHOUT ANY WARRANTY.
 * See the license for more details.
 *  
 * You should have received a copy of the GNU General Public License
 * along with LexiToolsMobile (see: gpl.txt); if not - you can find it 
 * on web page http://www.fsf.org/, or write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package lt.main;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

import lt.util.str;
import com.Callback;
import com.Receiver;
import com.SMSSender;
import lt.util.device;

// import org.netbeans.microedition.lcdui.wma.SMSComposer;

//#if MIDP=="1.0"
//# public class LexiToolsMidlet extends MIDlet implements Callback, CommandListener, ItemStateListener, Receiver {
//#else
public class LexiToolsMidlet extends MIDlet implements Callback, CommandListener, ItemStateListener, ItemCommandListener, Receiver {
//#endif    

    final background bkgrnd;
    final params par;
    final str ustr = new str();
    private SMSSender smsSender;
    private int SMS_state = 0;
    private Object SMS_semaphore = new Object();

    
    private Form frmEmpty;
    private Form frmMain;
    private Form frmSText;
    private Form frmSMS;
    private Form frmSettings;
    private Form frmDetail;
    private List listBrowser;
    private List listSelect;
    private Alert alertNote;
    private Alert alertSmsSend;
    
    private Command cmdMainSearch;
    private Command cmdMainSearchExamples;
    private Command cmdMainWebSearch;
    private Command cmdMainStoredText;
    private Command cmdMainClose;
    private Command cmdMainSettings;
    private Command cmdMainPreview;

    private Command cmdKeySearch;
    
    private Command cmdSTextExit;
    private Command cmdSTextBack;
    private Command cmdSTextPron0;
    private Command cmdSTextPron1;
    private Command cmdSTextSMS;
    private Command cmdSTextDelete;
    private Command cmdDetailBack;
    private Command cmdDetailStore;
    private Command cmdEditSMS;

    private Command cmdLangSMS;
    
    private Command cmdBrowserSelect;
    private Command cmdBrowserExit;

    private Command cmdSettingsFindDict;
    private Command cmdSettingsBack;
    private Command cmdSettingsSave;

    private Command cmdSmsSend;
    private Command cmdSmsExit;

    private Command cmdNodataCancel; 
    private Command cmdNodataAccept; 

    private Command cmdAcceptMessage;

//#if TESTING=="1"
//#     private Command cmdTesting;
//#endif
    
    private Font fontHelp2;
    private Image imgBrowse;                   

    private StringItem infoHelp1;
    private StringItem infoHelp2;
    private StringItem infoStoredText;
    private StringItem infoDetL0;
    private StringItem infoDetL1;
    private StringItem[] previews;
    
    private StringItem infoMessage;
    
    private TextField textKey;
    private TextField textNumber;
    private TextField textLang0;
    private TextField textLang1;

    private TextBox tboxEdMessage;

    private ChoiceGroup choiceIntLanguage;
    private ChoiceGroup choiceDirection;
/*
    private ChoiceGroup choiceDictionary;
    private ChoiceGroup choiceOptions;
*/
//#if MIDP=="1.0"
//#else    
    private Spacer spacer2;
//#endif	
    private boolean midletPaused = false;
    
    Runtime runtime;

    

/*********************** Fonts ******************************/
final int [] styles = {Font.STYLE_PLAIN, Font.STYLE_BOLD, Font.STYLE_ITALIC};
final int [] sizes = {Font.SIZE_SMALL, Font.SIZE_MEDIUM, Font.SIZE_LARGE};
final int [] faces = {Font.FACE_SYSTEM, Font.FACE_MONOSPACE, Font.FACE_PROPORTIONAL};

    
/*********************** MIDLET *****************************/
    
    public LexiToolsMidlet() {
       runtime = Runtime.getRuntime();
       par = new params();
       bkgrnd = new background(par, ustr);
    }

    private void initialize() {
    }

    public void startMIDlet() {
        switchDisplayable(null, get_frmMain());
    }
	
    public void resumeMIDlet() {
    }

    public Display getDisplay() {
        return Display.getDisplay(this);
    }

    public void exitMIDlet() {
        try {
            bkgrnd.stop();
            switchDisplayable (null, null);
            destroyApp(false);
        } catch (Throwable t) {
            t.printStackTrace();
        } finally {
            notifyDestroyed();
        }
    }

    public void switchDisplayable(Alert alert, Displayable nextDisplayable) {
        Display display = getDisplay();
        if (alert == null) {
            display.setCurrent(nextDisplayable);
        } else {
            display.setCurrent(alert, nextDisplayable);
        }
    }

    public void startApp() {
        if (midletPaused) {
            resumeMIDlet();
        } else {
            initialize();
            startMIDlet();
        }
        midletPaused = false;
    }

    public void pauseApp() {
        midletPaused = true;
//        resumeScreen = getDisplay().getCurrent();    
    }    
    
    private void freeControls() {
    listBrowser=null;
    listSelect=null;
    alertNote=null;
    alertSmsSend=null;
    
    cmdMainSearch=null;
    cmdMainSearchExamples=null;
    cmdMainWebSearch=null;
    cmdMainStoredText=null;
    cmdMainClose=null;
    cmdMainSettings=null;
    cmdMainPreview=null;

    cmdKeySearch=null;
    
    cmdSTextExit=null;
    cmdSTextBack=null;
    cmdSTextPron0=null;
    cmdSTextPron1=null;
    cmdSTextSMS=null;
    cmdSTextDelete=null;
    cmdDetailBack=null;
    cmdDetailStore=null;
    cmdAcceptMessage=null;
    cmdEditSMS = null;

    cmdLangSMS=null;
    
    cmdBrowserSelect=null;
    cmdBrowserExit=null;

    cmdSettingsFindDict=null;
    cmdSettingsBack=null;
    cmdSettingsSave=null;

    cmdSmsSend=null;
    cmdSmsExit=null;

    cmdNodataCancel=null; 
    cmdNodataAccept=null; 

//#if TESTING=="1"
//#     cmdTesting=null;
//#endif
    
    fontHelp2=null;
    imgBrowse=null;                   

    infoHelp1=null;
    infoHelp2=null;
    infoStoredText=null;
    infoDetL0=null;
    infoDetL1=null;
    
    textKey=null;
    textNumber=null;
    infoMessage = null;
    textLang0=null;
    textLang1=null;

    choiceIntLanguage=null;
    choiceDirection=null;
//    choiceDictionary=null;
//    choiceOptions=null;

//#if MIDP=="1.0"
//#else    
    spacer2=null;
//#endif
    frmMain=null;
    frmSText=null;
    frmSMS=null;
    frmSettings=null;
    frmDetail=null;
    tboxEdMessage=null;
    System.gc();
    }

    public void destroyApp(boolean unconditional) {
        previews=null;
        freeControls();
        frmEmpty=null;
    }

/* Callback */
public void cb_completed(int task, String msg) {
  if (task==0) {
    getDisplay().setCurrent(get_alertSmsSend(par.sSMS_WAS_SEND), get_frmMain());
    synchronized( SMS_semaphore ) { SMS_state=0; }
  } else if (task==1) {
      if (msg==null) {
        getDisplay().setCurrent(get_alertNote(par.sNUMBER_OF_DICT),  get_frmMain());
      } else {
        getDisplay().setCurrent(get_alertNote(par.sNUMBER_OF_DICT+msg),  get_frmMain());
      }
  }
}
    
public void cb_failure(int task, String msg) {
  if (task==0) {
    if (msg==null) {
        getDisplay().setCurrent(get_alertSmsSend(msg), get_frmMain());
    }
    synchronized( SMS_semaphore ) { SMS_state=0; }
  } else if (task==1) {
    if (msg==null) {
        getDisplay().setCurrent(get_alertNote(msg),  get_frmMain());
    }
  }
}
    
    
// **************************   Receiver methods implementation ****************************************/

    public void received(String url, byte[] data, int len, int target) {
        int i1, i2, i, c;
        String s;
        
        c=0;
        if (target == par.iGET_LIST) {
            i1=0;
            i2=0;
            get_imgBrowse();
            while (i1<len) {
                i=0;
                while ((i1<len) && (data[i1] != '\n') && (i<162)) {
                    i++;
                    i1++;
                }
                s=new String(data,i2,i1-i2);
                if (c==0) { 
                    listBrowser.set(0, s, imgBrowse);
                }
                else {
                    listBrowser.append(s, imgBrowse);
                }
                c++;
                s=null;
                i1++;
                i2=i1;
            }
        } else if (target == par.iGET_PRON) { // wymowa
//            spellit(data, len);
        }
        if (c==0) {
            listBrowser.set(0, "?", null);
        }
    }

    public void failure(String url) {
    listBrowser.set(0, par.sNOT_FOUND_WEB, null);
    }
/*********************** Programm logic (actions) ************************************/
 private void safeSetString(TextField tf, String s)
  {
      try
      {
          if (tf.getMaxSize()<s.length()) tf.setString(s.substring(tf.getMaxSize()));
          else tf.setString(s);
      }
      catch (IllegalArgumentException e)
      {
      //
      }
  }

  
private void safeSetText(StringItem si, String s)
  {
      try
      {
          si.setText(s);
      }
      catch (IllegalArgumentException e)
      {
      //
      }
  }
    

public void commandAction(Command command, Displayable displayable) {
/* test:
        char[] k = new char[5];
        char c0,c1,c2,c3;
 */
try {
        
        if (displayable == frmMain) {
            if (command == cmdMainSearch) {
                get_listBrowser();
/* test
 k[4]=(char)0;
                for (c0='a';c0<='j';c0++) {
                for (c1='a';c1<='f';c1++) {
                for (c2='a';c2<='c';c2++) {
                for (c3='a';c3<='e';c3++) {
                    k[0]=c0;k[1]=c1;k[2]=c2;k[3]=c3;
                    bkgrnd.search(false, String.valueOf(k), listBrowser, get_imgBrowse());
           Thread t = Thread.currentThread();
           t.sleep( 50 );
                }}}}
 */
                bkgrnd.search(false,textKey.getString().toLowerCase(), listBrowser, get_imgBrowse());
                getDisplay().setCurrent(listBrowser);
            } else if (command == cmdMainSearchExamples) {
                get_listBrowser();
                bkgrnd.search(true,textKey.getString().toLowerCase(), listBrowser, get_imgBrowse());
                getDisplay().setCurrent(listBrowser);
            } else if (command == cmdMainStoredText) {
                getDisplay().setCurrent(get_frmSText());
            } else if (command == cmdMainClose) {
                exitMIDlet();
            } else if (command == cmdMainSettings) {
                getDisplay().setCurrent(get_frmSettings());
            } else if (command == cmdMainWebSearch) {
                get_listBrowser();
//#if MIDP=="1.0"
//#                 for (i=listBrowser.size()-1; i>=0; i--) {
//#                     listBrowser.delete(i);
//#                 }
//#else
                listBrowser.deleteAll();
//#endif                
                listBrowser.append(par.sSEARCH, null);
                bkgrnd.WebSearch(textKey.getString().toLowerCase(),this);
                getDisplay().setCurrent(listBrowser);
//#if TESTING=="1"
//#             } else if (command == cmdTesting) {
//#endif                
            }
            
        } else if (displayable == frmSText) {
            if (command == cmdSTextExit) {
                exitMIDlet();
            } else if (command == cmdSTextSMS) {
                get_frmSMS();
                composeSMS();
                getDisplay().setCurrent(frmSMS);
            } else if (command == cmdSTextPron0) {
               
            } else if (command == cmdSTextBack) {
                getDisplay().setCurrent(get_frmMain());
            } else if (command == cmdSTextDelete) {
		safeSetString(textLang0, "");
		safeSetString(textLang1, "");
            } else if (command == cmdSTextPron1) {
                
            }
        } else if (displayable == listBrowser) {
            if (command == cmdBrowserExit) {
                getDisplay().setCurrent(get_frmMain());
            } else if (command == cmdBrowserSelect) {
                getDisplay().setCurrent(get_frmDetail());
            }
        } else if (displayable == frmDetail) {
            if (command == cmdDetailBack) {
                getDisplay().setCurrent(listBrowser);
            }
            else if (command == cmdDetailStore) {
                getDisplay().setCurrent(get_listSelect());
            }
        } else if (displayable == listSelect) {
            if (command == List.SELECT_COMMAND) {
                listSelectAction();
            }
        } else if (displayable == frmSMS) {
            
             if (command == cmdSmsSend) {
                String smsPort = getAppProperty("SMS-Port");
/*                new Thread( 
                  new SMSSender(get_textNumber().getString(),smsPort,infoMessage.getText())
                ).start();
 */
                if (get_smsSender() != null) {
                    smsSender.send(this, smsPort, textNumber.getString(),get_infoStoredText().getText());
                }
            } else if (command == cmdSmsExit) {
                getDisplay().setCurrent(get_frmMain());
            }
 
        } else if (displayable == tboxEdMessage) {
            if (command == cmdAcceptMessage) {
                safeSetText(infoMessage,tboxEdMessage.getString());
                getDisplay().setCurrent(get_frmSMS());
            }
        } else if (displayable == frmSettings) {
            if (command == cmdSettingsSave) {
                new Thread(new Runnable() {
                    public void run() {
                        set_Settings();
                        if (par.paramsInRS) par.WriteSettingsRS();
                        else par.WriteSettingsPIM();
                    }
                }).start();
                getDisplay().setCurrent(get_frmMain());
                
            } else if (command == cmdSettingsBack) {
                getDisplay().setCurrent(get_frmMain());
            } else if (command == cmdSettingsFindDict) {
                bkgrnd.FindDicts(this);
            }
        } else if (displayable == alertNote) {
               switchDisplayable(null, get_frmMain());
        } else if (/*command == exitCommand ||*/ command == Alert.DISMISS_COMMAND) {
                destroyApp(false);
                notifyDestroyed();
        } 

       } catch(Exception e /* OutOfMemoryError error */ ) {
            e.printStackTrace();
            Alert memoryAlert = new Alert(
                    "Error (1):"+e.toString(),
                    e.toString(),
                    null,
                    AlertType.WARNING);
            getDisplay().setCurrent( memoryAlert );


        }
        
    }
     
 public void commandAction(Command command, Item item) {
  int i;
        
 try {
    if (command == cmdMainPreview) {

            i=0;
            while (i<previews.length) {
                if (item.equals(previews[i])) {
                    safeSetString(textKey, previews[i].getText());
//#if MIDP=="1.0"
//#else         
                     getDisplay().setCurrentItem(textKey);
//#endif            
                    break;
                }
                i++;
            }
        }
        else if (item == textKey) {
            if (command == cmdKeySearch) {
                get_listBrowser();
                bkgrnd.search(false,textKey.getString().toLowerCase(), listBrowser, get_imgBrowse());
                getDisplay().setCurrent(listBrowser);
            }
        }
        else if ((item == textLang0) || (item == textLang1)){
            if (command == cmdLangSMS) {
                get_frmSMS();
                composeSMS();
                getDisplay().setCurrent(frmSMS);
            }
        } else if (item == infoMessage) {
            if (command == cmdEditSMS) {
                try {
                    get_tboxEdMessage().setString(infoMessage.getText());
                }
                catch (IllegalArgumentException e)
                {
                //
                }
                getDisplay().setCurrent(tboxEdMessage);
            }
        }
        
/**********
 * if (item == textNumber) {
            if (command == cmdSmsSend) {
                if (!isValidPhoneNumber(textNumber.getString())) {
                    alertSmsError.setString(par.sALERT_NUMBER);
//                    getDisplay().setCurrent(get_alertSmsError(), get_frmSMS());
                    return;
                }
                switchDisplayable(null, get_waitSMS());
            }
        }
 ******************/
       } catch(Exception e) {
            e.printStackTrace();
            Alert memoryAlert = new Alert(
                    "Error (2)",
                    e.toString(),
                    null,
                    AlertType.WARNING);
            getDisplay().setCurrent( memoryAlert );


        }
    
}
    
   void composeSMS() {
        String s0=get_textLang1().getString();
        String s1=get_textLang0().getString();
        if ((s0!=null) && (!s0.equals(""))) {
            if ((s1!=null) && (!s1.equals(""))) {
                safeSetText(infoMessage, s0+"["+s1+"]");
            }
            else {
                safeSetText(infoMessage, s1);
            }
        }
        else if ((s1!=null) && (!s1.equals(""))) {
           safeSetText(infoMessage, s1);
        }

   }

    public void StoreItem() {
        safeSetString(get_textLang0(), get_infoDetL0().getText());
        safeSetString(get_textLang1(), get_infoDetL1().getText());
   }

    public void AppendItem() {
        String s, s1;

        s1=get_infoDetL0().getText();
        if ((s1!=null) && (!s1.equals(""))){
            s=get_textLang0().getString();
            if ((s!=null) && (!s.equals(""))) {
                s=s+" * "+s1;
                if (s.length()>160) s=s.substring(160);
                safeSetString(textLang0, s);
            }
            else textLang0.setString(s1);
        }
        s1=get_infoDetL1().getText();
        if ((s1!=null)&& (!s1.equals(""))) {
            s=get_textLang1().getString();
            if ((s!=null) && (!s.equals(""))) {
                s=s+" * "+s1;
                if (s.length()>160) s=s.substring(160);
                safeSetString(textLang1, s);
            }
            else textLang1.setString(s1);
        }
   }

    
   public void listSelectAction() {
   try {
        switch (get_listSelect().getSelectedIndex()) {
            case 0:
                StoreItem();
                get_frmSMS();
                composeSMS();
                getDisplay().setCurrent(frmSMS);
                break;
            case 1:
                AppendItem();
                get_frmSMS();
                composeSMS();
                getDisplay().setCurrent(frmSMS);
                break;
            case 2:
                StoreItem();
                getDisplay().setCurrent(get_frmMain());
                break;
            case 3:
                AppendItem();
                getDisplay().setCurrent(get_frmMain());
                break;
            case 4:
                getDisplay().setCurrent(get_frmMain());
                break;
        }
       } catch(Exception e /* OutOfMemoryError error */ ) {
            Alert memoryAlert = new Alert(
                    "Error (3)",
                    e.toString(),
                    null,
                    AlertType.WARNING);
            getDisplay().setCurrent( memoryAlert );


        }
    }
    
    public void browserSelect() {
        String s;
        int i;
        Image img;

       try {
        i = listBrowser.getSelectedIndex();
        if (i >= 0) {
            s=listBrowser.getString(listBrowser.getSelectedIndex());
            if (s==null) i=-1;
            else i=s.indexOf(" : ");
            if (i<0) {
                img=listBrowser.getImage(listBrowser.getSelectedIndex());
                if (img!=null) {
                    get_infoDetL0();
                    safeSetText(infoDetL0, s);
                    get_infoDetL1();
                    try {
                        s=listBrowser.getString(listBrowser.getSelectedIndex()+1);
                    }
                    catch (Exception e) {
                        s="";
                    }
                    safeSetText(infoDetL1, s);
                }
                else {
                    get_infoDetL1();
                    safeSetText(infoDetL1, s);
                    get_infoDetL0();
                    try {
                        s=listBrowser.getString(listBrowser.getSelectedIndex()-1);
                    }
                    catch (Exception e) {
                        s="";
                    }
                    safeSetText(infoDetL0, s);
                }
            } else if (i >= 0) {
                get_infoDetL0();
                if (i > 0) {
                    get_infoDetL0();
                    safeSetText(infoDetL0, s.substring(0,i));
                    get_infoDetL1();
                    safeSetText(infoDetL1, s.substring(i+3));
                }
                else {
                    safeSetText(infoDetL0, s);               
                }
            }
        }
       } catch(Exception e /* OutOfMemoryError error */ ) {
            e.printStackTrace();
            Alert memoryAlert = new Alert(
                    "Error (4)",
                    e.toString(),
                    null,
                    AlertType.WARNING);
            getDisplay().setCurrent( memoryAlert );


        }

    }

    public void itemStateChanged(Item item) {
        int i;
        
       try {
        if (item.equals(textKey)) {
            bkgrnd.SearchPreview(textKey.getString().toLowerCase(),previews);
        }
        else {
            i=0;
            while (i<previews.length) {
                if (item.equals(previews[i])) {
                    safeSetString(textKey, previews[i].getText());
                    break;
                }
                i++;
            }
        }
           } catch(Exception e /* OutOfMemoryError error */ ) {
            e.printStackTrace();
            Alert memoryAlert = new Alert(
                    "Error (5)",
                    e.toString(),
                    null,
                    AlertType.WARNING);
            getDisplay().setCurrent( memoryAlert );


        }
}

/******************* settings <-> screen controls     ************************************************/
    public void get_Settings() {
        get_frmSettings();
//        choiceOptions.setSelectedIndex(0, par.dictInWeb);
//        choiceOptions.setSelectedIndex(1, par.dictGetPronunciation);
//        choiceOptions.setSelectedIndex(2, par.dictOnlyDummy);
        choiceDirection.setSelectedIndex(0,false);
        choiceDirection.setSelectedIndex(1,false);
        choiceIntLanguage.setSelectedIndex(0, false);
        choiceIntLanguage.setSelectedIndex(1, false);
        choiceDirection.setSelectedIndex(par.dictDirection, true);
        choiceIntLanguage.setSelectedIndex(par.intLanguage, true);
//        choiceDictionary.setSelectedIndex(par.dictDummy, true);
    }
    
    public void set_Settings() {
        int l;
        
        l=par.intLanguage;
//        par.dictInWeb=(choiceOptions.getSelectedIndex()>=0);
//        par.dictGetPronunciation=(choiceOptions.getSelectedIndex()>=0);
//        par.dictOnlyDummy=(choiceOptions.getSelectedIndex()>=0);
        par.dictDirection=choiceDirection.getSelectedIndex();
        par.intLanguage=choiceIntLanguage.getSelectedIndex();
//        par.dictDummy=choiceDictionary.getSelectedIndex();
        if (l != par.intLanguage) {
            par.switchLang();
            getDisplay().setCurrent(get_frmEmpty());
            freeControls();
            getDisplay().setCurrent(get_frmMain());
        } else {
            get_textKey();
            if (par.dictDirection==0)  textKey.setLabel(par.sLANG0);
            else textKey.setLabel(par.sLANG1);
        }
    }                
/******************* functions returns an initiliazed instance of components  ************************/

    /* Commands */

    public Command get_cmdMainSearch() {
        if (cmdMainSearch == null) {
            cmdMainSearch = new Command(par.sSEARCH, Command.SCREEN, 1);
        }
        return cmdMainSearch;
    }

    public Command get_cmdMainSearchExamples() {
        if (cmdMainSearchExamples == null) {
            cmdMainSearchExamples = new Command(par.sSEARCH_EXAMPLES, Command.SCREEN, 1);
        }
        return cmdMainSearchExamples;
    }

    public Command get_cmdMainStoredText() {
        if (cmdMainStoredText == null) {
            cmdMainStoredText = new Command(par.sSTORED_TEXT, Command.SCREEN, 2);
        }
        return cmdMainStoredText;
    }
    
    public Command get_cmdMainWebSearch() {
        if (cmdMainWebSearch == null) {
            cmdMainWebSearch = new Command(par.sWEB_SEARCH, Command.SCREEN, 3);
        }
        return cmdMainWebSearch;
    }

    public Command get_cmdMainSettings() {
        if (cmdMainSettings == null) {
            cmdMainSettings = new Command(par.sSETTINGS, Command.HELP, 4);
        }
        return cmdMainSettings;
    }
   
    public Command get_cmdMainClose() {
        if (cmdMainClose == null) {
            cmdMainClose = new Command(par.sCLOSE, Command.EXIT, 5);
        }
        return cmdMainClose;
    }

    public Command get_cmdBrowserSelect() {
        if (cmdBrowserSelect == null) {
            cmdBrowserSelect = new Command(par.sSELECT, Command.SCREEN, 1);
        }
        return cmdBrowserSelect;
    }

    public Command get_cmdBrowserExit() {
        if (cmdBrowserExit == null) {
            cmdBrowserExit = new Command(par.sBACK, Command.BACK, 2);
        }
        return cmdBrowserExit;
    }

    public Command get_cmdSTextSMS() {
        if (cmdSTextSMS == null) {
            cmdSTextSMS = new Command(par.sSEND, Command.SCREEN, 1);
        }
        return cmdSTextSMS;
    }

    public Command get_cmdSTextBack() {
        if (cmdSTextBack == null) {
            cmdSTextBack = new Command(par.sBACK, Command.BACK, 2);
        }
        return cmdSTextBack;
    }

    public Command get_cmdSTextDelete() {
        if (cmdSTextDelete == null) {
            cmdSTextDelete = new Command(par.sCLEAR, Command.SCREEN, 3);
        }
        return cmdSTextDelete;
    }

    public Command get_cmdSTextPron0() {
        if (cmdSTextPron0 == null) {
            cmdSTextPron0 = new Command(par.sLANG0_PRON, Command.SCREEN, 4);
        }
        return cmdSTextPron0;
    }

    public Command get_cmdSTextPron1() {
        if (cmdSTextPron1 == null) {
            cmdSTextPron1 = new Command(par.sLANG1_PRON, Command.SCREEN, 5);
        }
        return cmdSTextPron1;
    }
    
    public Command get_cmdSTextExit() {
        if (cmdSTextExit == null) {
            cmdSTextExit = new Command(par.sCLOSE, Command.EXIT, 6);
        }
        return cmdSTextExit;
    }

    public Command get_cmdSmsSend() {
        if (cmdSmsSend == null) {
            cmdSmsSend = new Command(par.sSEND, Command.SCREEN, 1);
        }
        return cmdSmsSend;
    }

    public Command get_cmdSmsExit() {
        if (cmdSmsExit == null) {
            cmdSmsExit = new Command(par.sBACK, Command.BACK, 2);
        }
        return cmdSmsExit;
    }

    public Command get_cmdSettingsFindDict() {
        if (cmdSettingsFindDict == null) {
            cmdSettingsFindDict = new Command(par.sFIND_DICT, Command.SCREEN, 3);
        }
        return cmdSettingsFindDict;
    }

    public Command get_cmdSettingsBack() {
        if (cmdSettingsBack == null) {
            cmdSettingsBack = new Command(par.sBACK, Command.BACK, 1);
        }
        return cmdSettingsBack;
    }

    public Command get_cmdSettingsSave() {
        if (cmdSettingsSave == null) {
            cmdSettingsSave = new Command(par.sSAVE, Command.SCREEN, 2);
        }
        return cmdSettingsSave;
    }

    public Command get_cmdNodataAccept() {
        if (cmdNodataAccept == null) {
            cmdNodataAccept = new Command(par.sSEARCH, Command.SCREEN, 1);
        }
        return cmdNodataAccept;
    }

    public Command get_cmdNodataCancel() {
        if (cmdNodataCancel == null) {
            cmdNodataCancel = new Command(par.sBACK, Command.BACK, 2);
        }
        return cmdNodataCancel;
    }

    public Command get_cmdMainPreview() {
        if (cmdMainPreview == null) {
            cmdMainPreview = new Command(par.sSELECT, Command.ITEM, 1);
        }
        return cmdMainPreview;
    }
    
    public Command get_cmdKeySearch() {
        if (cmdKeySearch == null) {
            cmdKeySearch = new Command(par.sSEARCH, Command.ITEM, 1);
        }
        return cmdKeySearch;
    }
    
    public Command get_cmdLangSMS() {
        if (cmdLangSMS == null) {
            cmdLangSMS = new Command(par.sSEND, Command.ITEM, 1);
        }
        return cmdLangSMS;
    }
	
    public Command get_cmdDetailBack() {
        if (cmdDetailBack == null) {                                 
            cmdDetailBack = new Command(par.sBACK, Command.BACK, 1);                                   
        }                         
        return cmdDetailBack;
    }

    public Command get_cmdDetailStore() {
        if (cmdDetailStore == null) {                                 
            cmdDetailStore = new Command(par.sSTORE, Command.SCREEN, 2);
        }                         
        return cmdDetailStore;
    }

    
    public Command get_cmdEditSMS() {
        if (cmdEditSMS == null) {
            cmdEditSMS = new Command(par.sSMS_EDIT, Command.ITEM, 0);
        }
        return cmdEditSMS;
    }
    
    public Command get_cmdAcceptMessage() {
        if (cmdAcceptMessage == null) {
            cmdAcceptMessage = new Command("Ok", Command.OK, 0);
        }
        return cmdAcceptMessage;
    }
        
    
//#if TESTING=="1"
//#     public Command get_cmdTesting() {
//#         if (cmdTesting == null) {
//#             cmdTesting = new Command("TEST", Command.OK, 1);
//#         }
//#         return cmdTesting;
//#     }
//#endif
    /* Labels */

    public StringItem get_infoHelp1() {
        if (infoHelp1 == null) {
            infoHelp1 = new StringItem(par.sHASH_KEYBOARD, "\n\n");
        }
        return infoHelp1;
    }


    public StringItem get_infoHelp2() {
        if (infoHelp2 == null) {
            infoHelp2 = new StringItem(par.sABOUT_INFO, "");
//#if MIDP=="1.0"
//#else         
             infoHelp2.setFont(fontHelp2);
//#endif    
        }
        return infoHelp2;
    }

	
    public StringItem get_infoDetL0() {
        if (infoDetL0 == null) {                                 
            infoDetL0 = new StringItem(par.sLANG0, "");                                   
        }                         
        return infoDetL0;
    }
    
    public StringItem get_infoDetL1() {
        if (infoDetL1 == null) {                                 
            infoDetL1 = new StringItem(par.sLANG1, "");                                   
        }                         
        return infoDetL1;
    }
    
 
   public StringItem get_infoStoredText() {
        if (infoStoredText == null) {                                 
            infoStoredText = new StringItem(par.sSTORED_TEXT, "");                                   
        }
        try {
	  infoStoredText.setText(get_textLang1().getString()+"["+get_textLang0().getString()+"]");
        } catch (Exception e) {
            //
        }
        return infoStoredText;
    }

    public StringItem get_infoMessage() {
        if (infoMessage == null) {
            infoMessage = new StringItem(par.sMESSAGE, "");
            infoMessage.addCommand(get_cmdEditSMS());
            infoMessage.setItemCommandListener(this);
            infoMessage.setDefaultCommand(cmdEditSMS);
        }
        return infoMessage;
    }
       
   
    /* Spacer */
//#if MIDP=="1.0"
//#else    
    public Spacer get_spacer2() {
        if (spacer2 == null) {                                 
            spacer2 = new Spacer(1000, 1);                                   
        }                         
        return spacer2;
    }
//#endif
    
    /* Image */
    public Image get_imgBrowse() {
        if (imgBrowse == null) {                       
            try {                        
                imgBrowse = Image.createImage("/lt/images/l.png");
            } catch (java.io.IOException exception) {
                exception.printStackTrace();
            }                      
        }                       
        return imgBrowse;
    }                     
    
	/* Choice */
    public ChoiceGroup get_choiceIntLanguage() {
        if (choiceIntLanguage == null) {
            choiceIntLanguage = new ChoiceGroup(par.sINTERFACE, Choice.EXCLUSIVE, new String[] {
                par.sLANG0,
                par.sLANG1
            }, new Image[] {
                null,
                null
            });
        }
        if (par.intLanguage==0) {
            choiceIntLanguage.setSelectedFlags(new boolean[] {
                true,
                false
            });
        } else {
            choiceIntLanguage.setSelectedFlags(new boolean[] {
                false,
                true
            });
        }
        return choiceIntLanguage;
    }

    public ChoiceGroup get_choiceDirection() {
        if (choiceDirection == null) {
            choiceDirection = new ChoiceGroup(par.sTRANS_DIR, Choice.EXCLUSIVE, new String[] {
                par.sDIR01,
                par.sDIR10
            }, new Image[] {
                null,
                null
            });
        }
        if (par.dictDirection==0) {
            choiceDirection.setSelectedFlags(new boolean[] {
                true,
                false
            });
        } else {
            choiceDirection.setSelectedFlags(new boolean[] {
                false,
                true
            });
        }
        return choiceDirection;
    }

/*
   public ChoiceGroup get_choiceDictionary() {
        if (choiceDictionary == null) {
            choiceDictionary = new ChoiceGroup(par.sDUMMY_DICT, Choice.EXCLUSIVE, new String[] {"Og\u00F3lny M.T."}, new Image[] {null});
            choiceDictionary.setSelectedFlags(new boolean[] {true});
        }
        return choiceDictionary;
    }
*/
    
/*
 public ChoiceGroup get_choiceOptions() {
        if (choiceOptions == null) {
            choiceOptions = new ChoiceGroup(par.sOPTIONS, Choice.MULTIPLE, new String[] {
                par.sOPT_ONLY_FIRST,par.sOPT_SEARCH_WEB,par.sOPT_GET_PRON
            }, new Image[] {
                null,
                null,
                null
            });
            choiceOptions.setSelectedFlags(new boolean[] {
                false,
                false,
                false
            });
        }
        return choiceOptions;
    }
 */   
	
    /* TextFields */

    public TextField get_textKey() {
        if (textKey == null) {
            if (par.dictDirection==0)  textKey = new TextField(par.sLANG0, null, 80, TextField.ANY);
            else  textKey = new TextField(par.sLANG1, null, 80, TextField.ANY);
            
//#if MIDP=="1.0"
//#else
            textKey.addCommand(get_cmdKeySearch());
            textKey.setItemCommandListener(this);
            textKey.setDefaultCommand(cmdKeySearch);
//#endif    
        }
        return textKey;
    }

    public TextField get_textLang0() {
        if (textLang0 == null) {
            textLang0 = new TextField(par.sLANG0, null, 120, TextField.ANY);
//#if MIDP=="1.0"
//#else         
//!             textLang0.addCommand(get_cmdLangSMS());
//!             textLang0.setItemCommandListener(this);
//!             textLang0.setDefaultCommand(get_cmdLangSMS());
//#endif
        }
        return textLang0;
    }

    public TextField get_textLang1() {
        if (textLang1 == null) {
            textLang1 = new TextField(par.sLANG1, null, 120, TextField.ANY);
//#if MIDP=="1.0"
//#else         
//!             textLang1.addCommand(get_cmdLangSMS());
//!             textLang1.setItemCommandListener(this);
//!             textLang1.setDefaultCommand(get_cmdLangSMS());
//#endif
        }
        return textLang1;
    }
    
    public TextField get_textNumber() {
        if (textNumber == null) {
            textNumber = new TextField(par.sENTER_NUMBER, null, 120, TextField.PHONENUMBER);
            textNumber.setString("+48");
            textNumber.delete(0, 3);
        }
        return textNumber;
    }

    
    /* Forms */
 
    public Form get_frmMain() {
        int i;
        Font font = null;
        
        if (frmMain == null) {

            frmMain = new Form(par.sAPP_NAME, new Item[] {
                get_textKey()
            });
            previews=new StringItem[par.iPreviewMax];
            font = Font.getFont(faces [0], styles [0], sizes [1]);
            for (i=0;i<par.iPreviewMax;i++) {
                previews[i]=new StringItem(null, "");
//#if MIDP=="1.0"
//#else         
                 previews[i].addCommand(get_cmdMainPreview());
                 previews[i].setItemCommandListener(this);
                 previews[i].setDefaultCommand(cmdMainPreview);
                 previews[i].setFont (font);
                 previews[i].setLayout(/*Item.LAYOUT_LEFT | Item.LAYOUT_VCENTER |*/ previews[i].LAYOUT_NEWLINE_AFTER);
//#endif
                previews[i].setText(par.sBlank);
                frmMain.append(previews[i]);
            }
            previews[0].setText(par.sHASH_KEYBOARD);
//previews[0].setText(Device.getVendorName());
//previews[1].setText(Device.getPhoneType());
            font=null;
//#if MIDP=="1.0"
//#              frmMain.addCommand(get_cmdMainSearch());
//#else         
            if (par.iPLATFORM==device.iPLATFORM_SONY_ERICSSON) {
                frmMain.addCommand(get_cmdMainSearch());
            }
//#endif
            frmMain.addCommand(get_cmdMainSearchExamples());
            frmMain.addCommand(get_cmdMainWebSearch());
            frmMain.addCommand(get_cmdMainStoredText());
            frmMain.addCommand(get_cmdMainSettings());
            frmMain.addCommand(get_cmdMainClose());
//#if TESTING=="1"
//#             frmMain.addCommand(get_cmdTesting());
//#endif
            frmMain.setCommandListener(this);
            
            frmMain.setItemStateListener(this); // for textKey & previews
        }
        System.gc(); System.gc(); // System.gc(); garbage collection
//      previews[0].setText("Free Memory = " + runtime.freeMemory() + "\n");
//      previews[1].setText("Total Memory = " + runtime.totalMemory() + "\n");
        return frmMain;
    }
    

    public Form get_frmSText() {
        if (frmSText == null) {
            frmSText = new Form(null, new Item[] {
                get_textLang0(),
                get_textLang1()
            });
            frmSText.addCommand(get_cmdSTextBack());
            frmSText.addCommand(get_cmdSTextSMS());
            frmSText.addCommand(get_cmdSTextDelete());
//            frmSText.addCommand(get_cmdSTextPron0());
//            frmSText.addCommand(get_cmdSTextPron1());
            frmSText.addCommand(get_cmdSTextExit());
            frmSText.setCommandListener(this);
        }
        return frmSText;
    }

    public Form get_frmSMS() {
        if (frmSMS == null) {
            frmSMS = new Form(null, new Item[] {get_textNumber(), get_infoMessage()});
            frmSMS.addCommand(get_cmdSmsExit());
            frmSMS.addCommand(get_cmdSmsSend());
            frmSMS.setCommandListener(this);
        }
        return frmSMS;
    }

   
    public Form get_frmSettings() {
        if (frmSettings == null) {
            frmSettings = new Form(null, new Item[] {
                get_choiceIntLanguage(),
                get_choiceDirection()
            });
            frmSettings.addCommand(get_cmdSettingsBack());
//            frmSettings.addCommand(get_cmdSettingsFindDict());
            frmSettings.addCommand(get_cmdSettingsSave());
            frmSettings.setCommandListener(this);
        }
        return frmSettings;
    }

   public Form get_frmDetail() {
        get_infoStoredText();
        if (frmDetail == null) {                                 
//#if MIDP=="1.0"
//#             frmDetail = new Form(null, new Item[] { get_infoDetL0(), get_infoDetL1(), infoStoredText });
//#else    
            frmDetail = new Form(null, new Item[] { get_infoDetL0(), get_infoDetL1(), get_spacer2(), infoStoredText });
//#endif            
            frmDetail.addCommand(get_cmdDetailBack());
            frmDetail.addCommand(get_cmdDetailStore());
            frmDetail.setCommandListener(this);                                  
        }
        browserSelect();
        return frmDetail;
   }		

   public Form get_frmEmpty() {
        if (frmEmpty == null) {                                 
            frmEmpty = new Form(null, null);
        }
        return frmEmpty;
   }		
   
/* SMS 
public SMSComposer get_SmsComposer() {
        if (smsComposer == null) {
            smsComposer = new SMSComposer(getDisplay());
            smsComposer.setTitle("LexiTools - SMS");
            smsComposer.addCommand(SMSComposer.SEND_COMMAND);
            smsComposer.addCommand(get_cmdSmsExit());
            smsComposer.setCommandListener(this);
            smsComposer.setBGColor(-3355444);
            smsComposer.setFGColor(-16777216);
            smsComposer.setPhoneNumberLabel(par.sENTER_NUMBER);
            smsComposer.setMessageLabel(par.sMESSAGE);
        }
        String s0=get_textLang1().getString();
        String s1=get_textLang0().getString();
        if ((s0!=null) && (!s0.equals(""))) {
            if ((s1!=null) && (!s1.equals(""))) {
                smsComposer.setMessage(s0+"["+s1+"]");
            }
            else {
                smsComposer.setMessage(s1);
            }
        }
        else if ((s1!=null) && (!s1.equals(""))) {
           smsComposer.setMessage(s1);
        }
        
        return smsComposer;
    }   
*/

public TextBox get_tboxEdMessage() {
        if (tboxEdMessage == null) {
            tboxEdMessage = new TextBox("LexiTools - SMS", "", 160, TextField.ANY);
            tboxEdMessage.addCommand(get_cmdAcceptMessage());
            tboxEdMessage.setCommandListener(this);
        }
        tboxEdMessage.setString(infoMessage.getText());
        return tboxEdMessage;
    }
   
/* List */
    

    public List get_listBrowser() {
        if (listBrowser == null) {
            listBrowser = new List(null, Choice.IMPLICIT);
            listBrowser.addCommand(get_cmdBrowserExit());
//#if MIDP=="1.0"
//#else         
            listBrowser.setSelectCommand(get_cmdBrowserSelect());
             listBrowser.setFitPolicy(Choice.TEXT_WRAP_ON);
//#endif            
            listBrowser.setCommandListener(this);
            //? listBrowser.setSelectedFlags(new boolean[] { false, false });
        }
        return listBrowser;
    }

    public List get_listSelect() {
        if (listSelect == null) {
            listSelect = new List(par.sSELECT_ACTION, Choice.IMPLICIT);
            listSelect.append(par.sSELECT_STORE_SMS, null);
            listSelect.append(par.sSELECT_APPEND_SMS, null);
            listSelect.append(par.sSELECT_STORE_BACK, null);
            listSelect.append(par.sSELECT_APPEND_BACK, null);
            listSelect.append(par.sBACK, null);
//!            listSelect.setTicker(getTicker1());
            listSelect.setCommandListener(this);
            listSelect.setSelectedFlags(new boolean[] { true, false, false, false, false });
        }
        return listSelect;
    }

/* Alerts */

    public Alert get_alertNote(String msg) {
        if (alertNote == null) {
            alertNote = new Alert(par.sNOTE, msg, null, AlertType.INFO);
            alertNote.addCommand(get_cmdNodataAccept());
            alertNote.addCommand(get_cmdNodataCancel());
            alertNote.setCommandListener(this);
            alertNote.setTimeout(20);
        }
        return alertNote;
    }

    public Alert get_alertSmsSend(String msg) {
        if (alertSmsSend == null) {
            alertSmsSend = new Alert(par.sSMS_SENDING, msg, null, AlertType.CONFIRMATION);
            alertSmsSend.setTimeout(-2);
        }
        return alertSmsSend;
    }

/* others  */
    public SMSSender get_smsSender() {
        synchronized( SMS_semaphore ) { 
            if (SMS_state==0) {
                SMS_state=1;
                if (smsSender != null) smsSender = null;
                smsSender = new SMSSender();
                return smsSender;
            }
            else return null;
        }
    }
    
    
}
